import Postmate from 'postmate'
import type { ChildAPI } from 'postmate'
import type { MaybeRef } from 'vue'

export function usePostmateChild<T extends ChildAPI, U extends Recordable>(data: MaybeRef<U>) {
  const childInstance = shallowRef<T>()
  const postmate = shallowRef<Promise<ChildAPI>>()
  watch(
    () => unref(data),
    (val) => {
      postmate.value = new Postmate.Model(val)
      // When parent <-> child handshake is complete, events may be emitted to the parent
      postmate.value.then((instance) => {
        childInstance.value = instance as T
      })
    },
    {
      immediate: true,
      deep: true,
    },
  )

  onUnmounted(() => {
    childInstance.value = undefined
    postmate.value = undefined
  })
  return childInstance
}
